package com.eqdd.yiqidian.base;

import android.app.Activity;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.eqdd.annotation.api.DealCodeInjector;
import com.eqdd.yiqidian.R;
import com.eqdd.yiqidian.annotation.DealCode;
import com.eqdd.yiqidian.base.loading.INetLoadingView;
import com.eqdd.yiqidian.base.loading.waitdialog.DialogHelper;
import com.eqdd.yiqidian.bean.User;
import com.eqdd.yiqidian.rxbus2.RxBus;
import com.eqdd.yiqidian.ui.tongxunlu.StaffActivity;
import com.eqdd.yiqidian.utils.ActivityInterceptor;
import com.eqdd.yiqidian.utils.FileUtil;
import com.eqdd.yiqidian.utils.GreenDaoUtil;
import com.eqdd.yiqidian.utils.KeyboardUtil;
import com.eqdd.yiqidian.utils.LoginInterceptor;
import com.eqdd.yiqidian.utils.PermissionTipUtil;
import com.eqdd.yiqidian.utils.ToastUtil;
import com.jakewharton.rxbinding.view.RxView;
import com.tbruyelle.rxpermissions.RxPermissions;
import com.trello.rxlifecycle.components.support.RxAppCompatActivity;

import java.util.Date;
import java.util.Stack;
import java.util.concurrent.TimeUnit;

/**
 * Created by vzhihao on 2016/11/2.
 */
public abstract class BaseActivity extends AppCompatActivity implements BaseView, View.OnClickListener {
    // 可以把常量单独放到一个Class中
    public static final String ACTION_NETWORK_CHANGE = "android.net.conn.CONNECTIVITY_CHANGE";
    public INetLoadingView netLoadingView;
    private long oldTime = 0;
    public BasePresenter basePresenter;
    public User user;
    public boolean isKeyBoardJustPan = true;

    private Bundle savedInstanceState;
    private int[] codes;
    private DealCode annotation;
    protected Object register;
    protected boolean isDealCode = false;
    protected boolean isRxbus = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        this.savedInstanceState = savedInstanceState;
        if (isKeyBoardJustPan) {
            getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        }
//        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        if (AppConstent.user == null) {
            AppConstent.user = GreenDaoUtil.getUser();
        }
        user = AppConstent.user;
        if (user == null) {
            LoginInterceptor.interceptor(this, getLocalClassName(), bundle -> {
                decorate();
            });
        } else {
            decorate();
        }
    }

    private void decorate() {
        netLoadingView = new DialogHelper(this);
        basePresenter = new BasePresenter();
        initBinding();
        removePush(true);
        initData();
        setView();
        if (isDealCode) {
            register = DealCodeInjector.register(this, RxBus.class);
        }
        if (isRxbus) {
            RxBus.getDefault().register(this);
        }
        lastRun();
    }

    protected void lastRun() {

    }

    private void removePush(boolean isFirst) {
        if (isFirst) {
            annotation = getClass().getAnnotation(DealCode.class);
            if (annotation != null) {
                codes = annotation.codes();
                for (int code : codes) {
                    if (GreenDaoUtil.getNum(code) != 0) {
                        GreenDaoUtil.setNum(code, 0);
                    }
                }
            }
        } else if (annotation != null) {
            for (int code : codes) {
                if (GreenDaoUtil.getNum(code) != 0) {
                    GreenDaoUtil.setNum(code, 0);
                }
            }
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Config.LOGIN && resultCode == Config.LOGIN_BACK) {
            if (AppConstent.user == null) {
                AppConstent.user = GreenDaoUtil.getUser();
            }
            user = AppConstent.user;
            decorate();
        }
    }

    /**
     * 使用 Universal 作为图片加载器时，保存图片到相册使用的方法
     *
     * @param imageView
     */
    protected void saveImageByUniversal(ImageView imageView) {
        RxPermissions.getInstance(this).request(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(isGrant -> {
                    if (isGrant) {
                        BitmapDrawable bmpDrawable = (BitmapDrawable) imageView.getDrawable();
                        MediaStore.Images.Media.insertImage(
                                getContentResolver(),
                                bmpDrawable.getBitmap(),
                                String.valueOf(System.currentTimeMillis()),
                                "");
                        ToastUtil.showShort("已保存到相册");
                    } else {
                        PermissionTipUtil.tip(this, "存储");
                    }
                });

    }

    protected void saveImageByUniversal(Bitmap bitmap) {
        RxPermissions.getInstance(this).request(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(isGrant -> {
                    if (isGrant) {
                        FileUtil.saveImageToGallery(this, bitmap);

                        ToastUtil.showShort("已保存到相册");
                    } else {
                        PermissionTipUtil.tip(this, "存储");
                    }
                });

    }

    protected String getText(TextView textView) {
        return TextUtils.isEmpty(textView.getText()) ? " " : textView.getText().toString();
    }

    public void recoverData() {

    }

    public Bundle getSavedInstanceState() {
        return savedInstanceState;
    }


    /**
     * 绑定初始化,加载网络数据时，root要赋值
     */
    public abstract void initBinding();

    /**
     * 初始化数据
     */
    public abstract void initData();


    /**
     * 设置各种view
     */
    public abstract void setView();


    @Override
    public void onBackPressed() {
        KeyboardUtil.hideSoftInput(this);
        Stack<Activity> allActivities = AppManager.getAppManager().getAllActivities();
        if (allActivities.size() <= 1) {
            long nowTime = new Date().getTime();
            if (nowTime - oldTime <= 2000) {
                AppManager.getAppManager().AppExit(this);
            } else {
                oldTime = nowTime;
                ToastUtil.showShort("再次点击退出程序");
            }
        } else {
            super.onBackPressed();
        }
    }


    @Override
    protected void onDestroy() {
        if (isDealCode) {
            DealCodeInjector.unregister(this, RxBus.class, register);
        }
        if (isRxbus) {
            RxBus.getDefault().unregister(this);
        }
        removePush(false);
        super.onDestroy();
        basePresenter.onUnsubscribe();


    }


    /**
     * [页面跳转]
     *
     * @param clz
     */
    public void startActivity(Class<?> clz) {
//        ActivityInterceptor.interceptor(this,clz,null,(bun) -> {
        startActivity(clz, null);
//        });
    }

    /**
     * [页面跳转]
     *
     * @param clz
     */
    public void startActivity(Class<?> clz, boolean isGreen) {
//        ActivityInterceptor.interceptor(this,clz,null,(bun) -> {
        if (isGreen) {
            startActivity(clz, null, true);

        } else {
            startActivity(clz, null);
        }
//        });
    }

    /**
     * [携带数据的页面跳转]
     *
     * @param clz
     * @param bundle
     */
    public void startComActivity(Class<?> clz, Bundle bundle) {
        Intent intent = new Intent();
        intent.setClass(this, clz);
        ActivityCompat.startActivity(this, intent, bundle);
    }


    /**
     * [携带数据的页面跳转]
     *
     * @param clz
     * @param bundle
     */
    public void startActivity(Class<?> clz, Bundle bundle) {
        ActivityInterceptor.interceptor(this, clz, bundle, (bun) -> {
            Intent intent = new Intent();
            intent.setClass(this, clz);
            if (bun != null) {
                intent.putExtras(bun);
            }
            startActivity(intent);
        });
    }

    /**
     * [携带数据的页面跳转]
     *
     * @param clz
     * @param bundle
     */
    public void startActivity(Class<?> clz, Bundle bundle, boolean isGreen) {
        if (isGreen) {
            Intent intent = new Intent();
            intent.setClass(this, clz);
            if (bundle != null) {
                intent.putExtras(bundle);
            }
            startActivity(intent);
        } else {
            ActivityInterceptor.interceptor(this, clz, bundle, (bun) -> {
                Intent intent = new Intent();
                intent.setClass(this, clz);
                if (bun != null) {
                    intent.putExtras(bun);
                }
                startActivity(intent);
            });
        }
    }

    /**
     * [含有Bundle通过Class打开编辑界面]
     *
     * @param cls
     * @param bundle
     * @param requestCode
     */
    public void startActivityForResult(Class<?> cls, Bundle bundle,
                                       int requestCode) {
        ActivityInterceptor.interceptor(this, cls, bundle, (bun) -> {
            Intent intent = new Intent();
            intent.setClass(this, cls);
            if (bun == null) {
                bun = new Bundle();
            }
            bun.putInt("requestCode", requestCode);
            intent.putExtras(bun);
            startActivityForResult(intent, requestCode);
        });
    }

    /**
     * [含有Bundle通过Class打开编辑界面]
     *
     * @param cls
     * @param bundle
     * @param requestCode
     */
    public void startActivityForResult(Class<?> cls, Bundle bundle,
                                       int requestCode, boolean isGreen) {
        if (isGreen) {
            Intent intent = new Intent();
            intent.setClass(this, cls);
            if (bundle == null) {
                bundle = new Bundle();
            }
            bundle.putInt("requestCode", requestCode);
            intent.putExtras(bundle);
            startActivityForResult(intent, requestCode);
        } else {
            ActivityInterceptor.interceptor(this, cls, bundle, (bun) -> {
                Intent intent = new Intent();
                intent.setClass(this, cls);
                if (bun == null) {
                    bun = new Bundle();
                }
                bun.putInt("requestCode", requestCode);
                intent.putExtras(bun);
                startActivityForResult(intent, requestCode);
            });
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        // 你可以添加多个Action捕获
        user = GreenDaoUtil.getUser();
        IntentFilter filter = new IntentFilter();
        filter.addAction(ACTION_NETWORK_CHANGE);
//        registerReceiver(receiver, filter);
        //还可能发送统计数据，比如第三方的SDK 做统计需求
    }

    @Override
    protected void onPause() {
        super.onPause();
//        unregisterReceiver(receiver);
        //还可能发送统计数据，比如第三方的SDK 做统计需求
    }
//
//    BroadcastReceiver receiver = new BroadcastReceiver() {
//        @Override
//        public void onReceive(Context context, Intent intent) {
//            // 处理各种情况
//            String action = intent.getAction();
//            if (ACTION_NETWORK_CHANGE.equals(action)) { // 网络发生变化
//                // 处理网络问题
//
//
//            }
//        }
//    };

    public void initTopTitleBar(int visible, String title, int resBg) {
        RelativeLayout rl_title = (RelativeLayout) findViewById(R.id.rl_title);
        rl_title.setBackgroundColor(resBg);
        ImageView back = (ImageView) findViewById(R.id.back);
        back.setVisibility(visible);
        if (visible == View.VISIBLE) {
            back.setOnClickListener(this);
        }
        TextView topbar_title = (TextView) findViewById(R.id.tv_title);
        topbar_title.setText(title);
    }

    public void initTopTitleBar(int visible, String title) {
        ImageView back = (ImageView) findViewById(R.id.back);
        if (back == null)
            return;
        back.setVisibility(visible);
        if (visible == View.VISIBLE) {
            back.setOnClickListener(this);
        }
        TextView topbar_title = (TextView) findViewById(R.id.tv_title);
        topbar_title.setText(title);
    }

    public void initTopTitleBar(int visible) {
        initTopTitleBar(visible, "");
    }

    public void initTopRightText(String title, View.OnClickListener onClickListener) {
        TextView textView = (TextView) findViewById(R.id.tv_right);

        if (textView == null) {
            return;
        }
        textView.setText(title);
        textView.setVisibility(View.VISIBLE);
        if (onClickListener != null) {
            RxView.clicks(textView)
                    .throttleFirst(1, TimeUnit.SECONDS)
                    .subscribe((o) ->
                            onClickListener.onClick(textView));
        }
    }

    public void initTopRightImage(int resId, View.OnClickListener onClickListener) {
        ImageView imageView = (ImageView) findViewById(R.id.iv_right);
        imageView.setImageResource(resId);
        imageView.setVisibility(View.VISIBLE);
        if (onClickListener != null) {
            RxView.clicks(imageView)
                    .throttleFirst(1, TimeUnit.SECONDS)
                    .subscribe((o) ->
                            onClickListener.onClick(imageView));
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back:
                onBackPressed();
                break;
        }
    }

    @Override
    public void showLoading() {
        netLoadingView.showLoading();
    }

    @Override
    public void showLoading(String msg) {
        netLoadingView.showLoading(msg);
    }

    @Override
    public void hideLoading(String msg) {
        netLoadingView.hideLoading(msg);
    }

    @Override
    public void hideLoading() {
        netLoadingView.hideLoading();

    }
}
